// pages/home/home.ts
import { login, isLogin } from '../../utils/login'
import { getAvatar } from '../../utils/getAvatar'
import { getUserInfo } from '../../api/login'
import { flow } from '../../utils/flowtype';



const plugin = requirePlugin('WechatSI');
const manager = plugin.getRecordRecognitionManager();

Page({

  /**
   * 页面的初始数据
   */
  data: <any>{
    selectlistHide: false, //列表展示
    replyed: true, //提问中
    content: "", //问题

    tagstype: true, //输入框高度类名
    voiceing: false, //是否处于语音输入中
    voicedelay: true, //语音图片延迟展示否则可能会闪现

    tools: [{
      id: 1,
      name: '问答助手',
      icon: 'iconQ.svg',
      iconHot: 'iconQ-w.svg',
      params: {
        id: 1
      }
    }, {
      id: 2,
      name: '指南解读',
      icon: 'iconLearn.svg',
      iconHot: 'iconLearn-w.svg',
      params: {
        id: 2
      }
    }],

    currentEntry: 1,
    
    originAnswers: [], 
    answers: [],
    problemList: [],
    show: false,

    probe: [], //追问的内容数据
    waiting: "", //等候语

    article: "", //markdown
    problemlogo: "",  //提问的头像
    newContent: "", //流式输出文本
    chatdata: [], //获取chat的url之类的数据

    voice_type: "", //合成声音的音色
    novoice: true, //是否播放语音
    voicelist: '', //音频的列表数据

    requestTask: "", //请求实例

    dreplyedList: [], // 给列表传递的内容数据
    bottomId: '',
    time: null
  },
  
  onLoad() {
    this.setData({
      problemlogo: "我",
      waiting: this.markdown("思考中，请稍后...")
    })
    this.initRecord()
    this.getRouterdata()
    wx.onKeyboardHeightChange(res => {
      console.log(res.height)
    })
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }

    if (isLogin()) {
      this.init()
    }
  },

  getRouterdata() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', (data) => {
      if(!data && data.data){
        return
      }
      const guide = data.data
      this.setData({
        currentGuide: guide
      })
      this.chatinit();
    })
  },

  // 获取chat数据
  async chatinit() {
    this.addAnswersList({
      role: "assistant",
      content: this.markdown(`您好，我是您的《${this.data.currentGuide.name}》AI助手，有什么可以帮助您？`)
    })
    
    this.saveOriginAnswerList({
      role: "assistant",
      content: `您好，我是您的《${this.data.currentGuide.name}》AI助手，有什么可以帮助您？`
    })

    // 初始化3个问题
    let recommend: any = this.data.currentGuide.problemList || []
    this.setData({
      probe: recommend
    })
  },

  async init() {
    const userInfo = login()
    if (userInfo) {
      this.handleLoginAction(userInfo);
      this.getAvatarHandle()
    }
    this.getInfo()
  },

  getInfo() {
    getUserInfo().then((res: any) => {
      let userInfo = res.user;
      if (userInfo) {
        wx.setStorageSync('userInfo', userInfo);
        this.handleLoginAction(userInfo)
      }
    })
  },

  getAliDeep() {
    return {
      url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
      token: 'sk-218d285e344c4b968d1b383c500ebe7b',
      data: {
        "model": "deepseek-r1",
        "stream": true,
        "messages": this.data.originAnswers
      }
    }
  },
  getCaCa() {
    return {
      url: 'https://caca.zn-care.com/api/v1/chat/completions/ask',
      token: wx.getStorageSync('token'),
      data: {
        "modelId": this.data.currentGuide.id,
        "stream": true,
        "messages": this.data.originAnswers
      }
    }
  },

  // 发送请求
  getFastGPTAns() {
    if (!this.data.replyed) {
      wx.showToast({
        title: '请等待上一次对话结束',
        icon: 'error',
        duration: 1000,
      })
      return
    }
    if (this.data.content == "") {
      wx.showToast({
        title: '问题不能为空',
        icon: 'error',
        duration: 1000,
      })
      return
    }

    // 等待60秒后，恢复可以输入
    this.setData({
      time: setTimeout(() => {
        this.setData({
          replyed: true
        })
      }, 60000)
    })

    if (this.data.replyed) {
      this.setData({
        replyed: false,
      })

      // 提问的内容显示出来
      this.addAnswersList({
        role: "user",
        problem: this.data.content
      })

      // 等待中内容显示出去
      this.addAnswersList({
        role: "assistant",
        content: this.data.waiting
      })
      this.saveOriginAnswerList({
        role: "user",
        content: this.data.content
      })

      const { url, token, data } = this.getCaCa()
      const requestTask = wx.request({
        url,
        method: "POST",
        enableChunked: true,
        header: {
          "Authorization": `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        data,
        success: () => {
          clearTimeout(this.data.time)
          this.setData({
            time: null,
            replyed: true
          })

          this.saveOriginAnswerList({
            role: "assistant",
            content: this.data.newContent
          })

          this.setData({
            newContent: ""
          })

          setTimeout(() => {
            this.scrollBottom()
          }, 1000)
        },
        fail: () => {
          clearTimeout(this.data.time)
          this.setData({
            time: null,
            replyed: true
          })
        }
      })

      this.setData({
        requestTask: requestTask
      })

      // 监听数据分块接收事件，流式输出
      requestTask.onChunkReceived((response) => {
        let newContent = this.data.newContent
        let result = flow(response, newContent, this.data.answers)

        this.setData({
          newContent: result.newContent,
          answers: result.answers
        })

        this.throttleScrollBottom()
      });

    }
  },

  // 点击追问提问
  probeClick(e: any) {
    let index = e.currentTarget.dataset.index
    let text = this.data.entryDatas[this.data.showEntry].problemList[index]
    this.setData({
      content: text
    })
    this.getFastGPTAns()
  },

  // 问答模式添加数据
  addAnswersList(message: any) {
    const entryDatas = { ...this.data.entryDatas };
    entryDatas[this.data.showEntry].answers.push(message);
    this.setData({
      entryDatas
    });

    setTimeout(() => {
      this.clearTextarea()
      this.scrollBottom()
    }, 30)
  },

  saveOriginAnswerList(message: any) {
    const entryDatas = { ...this.data.entryDatas };
    entryDatas[this.data.showEntry].originAnswers.push(message);
    this.setData({
      entryDatas
    });
  },

  lastScrollTime: '',

  throttleScrollBottom() {
    const that = this;
    const step = 600;
    if (!this.data.lastScrollTime || (Date.now() - this.data.lastScrollTime) > step) {
      that.scrollBottom()
      this.data.lastScrollTime = Date.now();
    } else {
      clearTimeout(this.data.scrollTimeout);
      this.data.scrollTimeout = setTimeout(() => {
        that.scrollBottom();
      }, step - (Date.now() - this.data.lastScrollTime));
    }
  },

  scrollBottom() {
    this.setData({
      bottomId: 'dialogBottom'
    });
  },

  // 删除输入框
  clearTextarea: function () {
    this.setData({
      content: "",
    })
  },

  // markdown解析
  markdown(content: string) {
    let towxml = require('../../towxml/index')
    let result = towxml(content, 'markdown')
    return result
  },

  // 输入框高度动画
  changeFooterStyle() {
    this.setData({
      tagstype: !this.data.tagstype,
    })
  },

  initRecord: function () {
    const that = this;
    manager.onStop = function (res: any) {
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚，请重新说一遍！',
          showCancel: false,
          success: function (res: any) { }
        })
        return;
      }
      that.setData({
        content: res.result
      })
    }
  },

  touchStart() {
    manager.start({
      lang: 'zh_CN',
    })
    this.setData({
      voicedelay: false
    })
    setTimeout(() => {
      this.setData({
        voiceing: !this.data.voiceing,
      })
    }, 300)
  },

  touchEnd() {
    manager.stop();
    this.setData({
      voiceing: !this.data.voiceing,
      voicedelay: true
    })
  },


  getAvatarHandle() {
    if (this.data.avatar) {
      return
    }
    const avatar = getAvatar(this)
    this.setData({
      avatar: avatar || getApp().globalData.defaultAvatar
    })
  },

  handleLoginAction(userInfo: any) {
    this.setData({
      userInfo: userInfo,
      logined: true,
      show: false
    })
  },
  
  startEntry(e: any) {
    const { type, id } = e.currentTarget.dataset
    switch (type) {
      case '0':
        wx.switchTab({
          url: '/pages/question/question?id=' + id,
        });
        break;
      case '1':
        wx.switchTab({
          url: '/pages/case/case?id=' + id,
        });
        break;
    }
  },

  showEntry(e) {
    this.setData({
      currentEntry: 1
    });
  },
  
  back(){
    wx.navigateBack({
      delta: 1  // delta 值为 1 时表示关闭当前页面
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home`,
      "imageUrl": "/static/img/home.jpg"
    }
  },

  /**
   * 图片出错时，替换默认图片
   * @param e 
   */
  onError(e: any) {
    let { index, i } = e.currentTarget.dataset;
    let taskList = this.data.taskList;
    taskList[index].userList[i].avatar = getApp().globalData.defaultAvatar
    this.setData({
      taskList
    })
  },
})